//
//  KLineView.swift
//  Trans
//
//  Created by zcj on 2024/12/11.
//

import Foundation
import AppKit

class KLineView:NSView{
    //points
    var points:PointArr = PointArr()
    
    
    override func draw(_ dirtyRect: NSRect) {
        print("upate klineview draw")
        if points.arr.count < 2{
            return
        }
        
        //为了给上下留下一些空间，所以要减去一个固定的值 baseH*2
//        let baseH:CGFloat = self.bounds.height * 0.05
        let baseH:CGFloat = 10
        let height = self.bounds.height - (baseH * 2)
        let width = self.bounds.width
        
        NSColor.blue.setStroke()
        let lineWidth:CGFloat = 2.0
        let path = NSBezierPath()
        var count:CGFloat = 0
        
        var prePoint:CGPoint = CGPoint(x: 0, y: 0)
        for point in points.arr {
            let perc = getHPercent(point: point,prePoint: prePoint)
            prePoint = point
            let py = perc * height + baseH
            if point == points.arr.first{
                path.move(to: CGPoint(x: 0, y: py))
            }else{
                path.line(to: CGPoint(x: getWPercent(point: point) * width , y: py) )
            }
            count += 1
        }
        path.lineWidth = lineWidth
        path.stroke()
    }
    
    //计算高度的比例
    func getHPercent(point:CGPoint,prePoint:CGPoint) -> CGFloat {
        let widofTime = point.x - prePoint.x
        if 0 >= widofTime {
            return 0
        }
        let speed = (point.y - prePoint.y ) / widofTime
        let hp = speed / ( points.maxSpeed - points.minSpeed)
        return hp
    }
    
    func getWPercent(point:CGPoint) -> CGFloat {
        let firstX = points.arr.first!.x
        let width = points.lastPoint.x - firstX
        if 0 >= width {
            return 0
        }
        let wp = (point.x - firstX) / width
        return wp
        
    }
    
}
